package com.xiaolei.library.Net;

import android.content.Context;

import com.xiaolei.library.Provider.ContextProvider;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

import okhttp3.Dispatcher;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;

/**
 * 网络框架的核心所在
 */
public class BaseNetCore
{
    private final Retrofit retrofit;
    private final Map<Class<?>, Object> apis = new ConcurrentHashMap<>();

    /**
     * 网络核心模块初始化
     *
     * @param base_url 基础URL
     * @param config   初始化设置
     */
    public BaseNetCore(String base_url, BaseNetConfig config)
    {
        Context context = ContextProvider.context;

        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.proxy(config.proxy()) // 禁止代理抓包
                // 失败重连 
                .retryOnConnectionFailure(config.retryOnConnectionFailure())
                // 连接超时
                .connectTimeout(config.connectTimeout(), TimeUnit.SECONDS)
                // 读取超时
                .readTimeout(config.readTimeout(), TimeUnit.SECONDS)
                // 写出超时
                .writeTimeout(config.writeTimeout(), TimeUnit.SECONDS)
                // cookie支持
                .cookieJar(config.cookieJar(context));
        // 配置拦截器之前
        config.beforeAddInterceptor(builder, context);
        // 配置拦截器
        config.onAddInterceptor(builder, context);
        // 配置拦截器之后
        config.afterAddInterceptor(builder, context);
        // 构建
        OkHttpClient okHttpClient = builder.build();
        Dispatcher dispatcher = okHttpClient.dispatcher();
        // 最大主机数为 5*2 个
        dispatcher.setMaxRequestsPerHost(dispatcher.getMaxRequestsPerHost() * 2);
        // 最大请求数为 64*2 个
        dispatcher.setMaxRequests(dispatcher.getMaxRequests() * 2);

        Retrofit.Builder retrofitBuilder = new Retrofit.Builder().baseUrl(base_url); //02采用链式结构绑定Base url
        // 在添加转换器之前
        config.beforeAddConverterFactory(retrofitBuilder, context);
        // 添加转换器
        config.onAddConverterFactory(retrofitBuilder, context);
        // 在添加转换器之后
        config.afterAddConverterFactory(retrofitBuilder, context);

        retrofit = retrofitBuilder.client(okHttpClient).build(); //03执行操作
    }

    /**
     * 创建新的API
     */
    public <T> T create(Class<T> klass)
    {
        Object api = apis.get(klass);
        if (api == null)
        {
            api = retrofit.create(klass);
            apis.put(klass, api);
        }
        return (T) api;
    }
}
